/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * listEntrada.java
 *
 * Created on 15/12/2011, 22:56:32
 */
package visao;

import entrada.Entrada;
import fachada.FachadaBDR;
import fornecedor.Fornecedor;
import funcionario.Funcionario;
import java.sql.Date;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import util.KeyValue;
import util.Util;

/**
 *
 * @author Alberto
 */
public class listEntrada extends javax.swing.JFrame {
    
    public String[] titulos = new String [] {"#", "Fornecedor", "Funcionário", "Data Entrada", "Nota Fiscal", "Valor Total"};
    public DefaultTableModel defTable;
    public CadCompra cadastroCompra = new CadCompra(0);

    /** Creates new form listEntrada */
    public listEntrada() {
        try {
            FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();
            List<Entrada> listEmpresa = objfaFachadaBDR.listarEntradas();
            
            // Setando a tabela
            this.defTable = atualizaLista(listEmpresa);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        } 

        initComponents();
        this.setLocationRelativeTo(null);
        this.setIconImage(new ImageIcon(getClass().getResource("/Imagens/visao.gif")).getImage());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();
        mensagem = new javax.swing.JLabel();
        jComboBox_idFornecedor = new javax.swing.JComboBox();
        jComboBox_idFuncionario = new javax.swing.JComboBox();
        jFormattedTextField_data_compra_inicial = new javax.swing.JFormattedTextField();
        jFormattedTextField_data_compra_final = new javax.swing.JFormattedTextField();
        jLabel_idFornecedor = new javax.swing.JLabel();
        jLabel_idFuncionario = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton_Buscar = new javax.swing.JButton();

        setTitle("Entrada");
        setResizable(false);

        jTable1.setModel(this.defTable);
        jScrollPane1.setViewportView(jTable1);

        jButton2.setText("Excluir");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        try {
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();
            List<Fornecedor> listFornecedor = objFachadaBDR.listarFornecedor("");
            jComboBox_idFornecedor.addItem(new KeyValue("--- Favor Selecionar ---", "0"));
            for (Fornecedor objForn : listFornecedor) {
                jComboBox_idFornecedor.addItem(new KeyValue(objForn.getContato(), Integer.toString(objForn.getIdFornecedor())));
            }
        } catch (Exception e) {
        }
        jComboBox_idFornecedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox_idFornecedorActionPerformed(evt);
            }
        });

        try {
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

            List<Funcionario> listFuncionario = objFachadaBDR.listarFuncionario("");

            jComboBox_idFuncionario.addItem(new KeyValue("--- Favor Selecionar ---","0"));
            for (Funcionario objFuncionario : listFuncionario) {
                jComboBox_idFuncionario.addItem(new KeyValue(objFuncionario.getNome(), Integer.toString(objFuncionario.getIdFuncionario())));
            }

        } catch (Exception e) {
        }

        jFormattedTextField_data_compra_inicial = new JFormattedTextField(Util.setMascara("##/##/####"));
        jFormattedTextField_data_compra_inicial.setText("01/01/2001");

        jFormattedTextField_data_compra_final = new JFormattedTextField(Util.setMascara("##/##/####"));
        jFormattedTextField_data_compra_final.setText(Util.getDataAtual());

        jLabel_idFornecedor.setText("Fornecedor :");

        jLabel_idFuncionario.setText("Funcionario :");

        jLabel1.setText("Data Inicial:");

        jLabel2.setText("Data Final:");

        jButton_Buscar.setText("Buscar");
        jButton_Buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_BuscarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 552, Short.MAX_VALUE)
                    .addComponent(mensagem, javax.swing.GroupLayout.PREFERRED_SIZE, 543, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jFormattedTextField_data_compra_inicial, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(26, 26, 26)
                        .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 65, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jFormattedTextField_data_compra_final, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(43, 43, 43)
                        .addComponent(jButton_Buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(45, 45, 45))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(104, 104, 104)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addComponent(jLabel_idFuncionario)
                            .addGap(18, 18, 18)
                            .addComponent(jComboBox_idFuncionario, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addComponent(jLabel_idFornecedor)
                            .addGap(18, 18, 18)
                            .addComponent(jComboBox_idFornecedor, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox_idFornecedor, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel_idFornecedor))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox_idFuncionario, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel_idFuncionario))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jFormattedTextField_data_compra_inicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jFormattedTextField_data_compra_final, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jButton_Buscar))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 352, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(mensagem, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        try {
            // pegando a linha selecionada
            if (this.jTable1.getSelectedColumnCount() == 0 || this.jTable1.getSelectedColumnCount() > 1) {
                throw new Exception("Favor selecionar um Produto");
            }

            int cancelar = JOptionPane.showConfirmDialog(null, "Deseja Remover esta Entrada Material?");
            if (cancelar == JOptionPane.YES_OPTION) {
                try {
                    int linha = this.jTable1.getSelectedRow();

                    // recuperando o Cpf do funcionario
                    int idEntrada = (Integer) this.jTable1.getValueAt(linha, 0);

                    FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();
                    
                    // recuperando a entrada pelo ids
                    Entrada objEntrada = objFachadaBDR.procurarEntrada(idEntrada);
                    
                    // removendo a entrada da base
                    objFachadaBDR.cancelarEntrada(objEntrada);
                    
                    // listandos todas as entradas da base
                    List<Entrada> listEmpresa = objFachadaBDR.listarEntradas();

                    // Setando a tabela
                    this.defTable = atualizaLista(listEmpresa);

                    // Setando a nova listagem
                    jTable1.setModel(this.defTable);

                    jTable1.revalidate();

                    mensagem.setText("Removido com sucesso!");

                } catch (Exception ex) {
                    mensagem.setText(ex.getMessage());
                }
            }
        } catch (Exception e) {
            mensagem.setText(e.getMessage());
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jComboBox_idFornecedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_idFornecedorActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_jComboBox_idFornecedorActionPerformed

    private void jButton_BuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_BuscarActionPerformed
        try {
            // instanciando a fachada
            FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();
            
            int idFornecedor = Integer.parseInt(((KeyValue) jComboBox_idFornecedor.getSelectedItem()).getValue());
            int idFuncionario = Integer.parseInt(((KeyValue) jComboBox_idFuncionario.getSelectedItem()).getValue());
            Date dataSolicitacaoInicial = Date.valueOf(Util.formatarDataBanco(jFormattedTextField_data_compra_inicial.getText()));
            Date dataSolicitacaoFinal = Date.valueOf(Util.formatarDataBanco(jFormattedTextField_data_compra_final.getText()));
            
            //            idFornecedor, idSolicitacaoCompra, idFuncionario, dataSolicitacao
            
            // Listando as descrição produtos
            List<Entrada> listEntrada = objfaFachadaBDR.listarEntradaPorFornecedorPorFuncionarioPorData(idFornecedor, idFuncionario, dataSolicitacaoInicial, dataSolicitacaoFinal) ;
            
            // Setando a tabela
            this.defTable =  atualizaLista(listEntrada);
            
            // Setando a nova listagem
            jTable1.setModel(this.defTable);
            jTable1.revalidate();
            
            if(listEntrada.size() > 0)
                mensagem.setText("");
            else
                mensagem.setText("Nenhuma Descrição Produto encontrada!");
        } catch (Exception ex) {
            mensagem.setText(ex.getMessage());
        }
}//GEN-LAST:event_jButton_BuscarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new listEntrada().setVisible(true);
            }
        });
    }
    
    public DefaultTableModel atualizaLista(List<Entrada> listEntrada) {
        //{"#", "Fornecedor", "Funcionário", "Data Entrada", "Nota Fiscal", "Valor Total",
        Object[][] resposta = new Object[listEntrada.size()][6];

        for (int i = 0; i < resposta.length; i++) {
            Entrada objEntrada = listEntrada.get(i);

            resposta[i][0] = objEntrada.getIdEntrada();
            resposta[i][1] = objEntrada.getFornecedor().getDescricaoFornecedor();
            resposta[i][2] = objEntrada.getFuncionario().getNome();
            resposta[i][3] = Util.formatarBancoData(objEntrada.getDataEntrada().toString());
            resposta[i][4] = objEntrada.getNumeroNota();
            resposta[i][5] = objEntrada.getTotalNotas();
        }
        // Setando a tabela
        return new DefaultTableModel(resposta, titulos){   
              @Override  
              public boolean isCellEditable(int row, int col)   
              {   
                     return false;   
              }   
        };
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton_Buscar;
    private javax.swing.JComboBox jComboBox_idFornecedor;
    private javax.swing.JComboBox jComboBox_idFuncionario;
    private javax.swing.JFormattedTextField jFormattedTextField_data_compra_final;
    private javax.swing.JFormattedTextField jFormattedTextField_data_compra_inicial;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel_idFornecedor;
    private javax.swing.JLabel jLabel_idFuncionario;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel mensagem;
    // End of variables declaration//GEN-END:variables
}
